<template>
  <el-dialog v-model="dialogTableVisible" title="权限设置" width="800" :before-close="handleClose">
    <el-tree
        ref="treeRef"
        style="max-width: 600px"
        :data="rowData.data"
        show-checkbox
        node-key="id"
        default-expand-all
        :props="defaultProps"
    />
    <el-button type="primary" @click="save">保存</el-button>
  </el-dialog>
</template>

<script setup>
import { ref,reactive,nextTick } from 'vue'
import {_getAllRole, _getUserRoleListBtn, _updateRole} from "../../http/api.js";
import {ElMessage} from "element-plus";

const $emit = defineEmits(['showRoleEmit'])
const props = defineProps({
  userId: String,
  roleId: String,
})
const treeRef = ref()
const dialogTableVisible = ref(false); //
const defaultProps = {
  children: 'children',
  label: 'label',
}
const rowData = reactive({
  data:[]
})
// 获取用户树形
const getAllRole = () => {
  _getAllRole(props.userId)
      .then(res => {
        console.log(res);
        if(res.data.ok) {
          let item = res.data.data;
          rowData.data = item;
          dialogTableVisible.value = true;
          getUserRoleListBtn(props.userId)
        }
      })
      .catch(err => {
        console.log(err);
      })
}
getAllRole();
// 关闭回调
const handleClose = () => {
  $emit('showRoleEmit')
}
// 根据用户id获取权限列表
const getUserRoleListBtn = (id) => {
  _getUserRoleListBtn(id)
      .then(res => {
        console.log(res);
        if(res.data.ok) {
          let arrData = res.data.data||[];
          nextTick(() => {
            disposeDefaultChecked(arrData);
          })
        }
      })
      .catch(err => {
        console.log(err);
      })
}

// 处理默认选中
const disposeDefaultChecked = (arrData) => {
  if(arrData.length <= 0) return arrData;
  arrData.forEach(v => {
    if(v.children && v.children.length > 0) {
      disposeDefaultChecked(v.children);
    }else {
      treeRef.value.setChecked(v.id,true)
    }
  })
}
//保存
const save = () => {
  let data = treeRef.value.getCheckedNodes();
  console.log(data);
  let menuId = [];
  data.forEach(v => {
    menuId.push(v.id)
  })
  let params = {
    id:props.userId,
    roleId: props.roleId,
    menuId: menuId.toString()
  }
  console.log(params);
  updateRole(params)
}
// 提交更新权限
const updateRole = (params) => {
  _updateRole(params)
      .then(res => {
        console.log(res);
        if(res.data.ok) {
          ElMessage({type: 'success', message: '更新成功'})
          handleClose()
        }else{
          ElMessage({type: 'error', message: res.data.msg })
        }
      })
      .catch(err => {
        console.log(err);
      })
}
</script>

<style scoped lang="scss">

</style>